# 初始化部分
from flask import Flask,render_template,request,abort,send_file, send_from_directory,make_response,Response
from pyecharts.options import charts_options
from pyecharts.options.charts_options import PieItem
from werkzeug.utils import secure_filename
import leancloud
import os
import time
import xlsxwriter
import uuid
import requests
from io import BytesIO
from PIL import Image
import math
from pyecharts.charts import Pie
from pyecharts import options as opts
from jinja2 import Markup
from pyecharts.globals import WarningType
import collections
WarningType.ShowWarning = False
leancloud.init(os.environ['LEANCLOUD_APP_ID'],os.environ['LEANCLOUD_APP_KEY'] )
Classmate=leancloud.Object.extend("Classmate")
if "BEIAN" in os.environ:
    beian=os.environ['BEIAN']
else:
    beian=""
title=os.environ['TITLE']
limit=int(os.environ['LIMIT'])
app = Flask(__name__)
# 主页部分
@app.route("/",methods = ['POST', 'GET'])
def submit():
    global Classmate
    global beian
    global title
    query=Classmate.query
    query.exists('Name')
    number=query.count()
    if request.method == 'POST':
        success=True
        content=request.form
        classmate=Classmate()
        classmate.set('Name',content['Name'])
        classmate.set('Birthday',content['Birthday'])
        classmate.set('Address',content['Address'])
        classmate.set('Sex',content['Sex'])
        classmate.set('Wechat',content['Wechat'])
        classmate.set("QQ",content['QQ'])
        classmate.set("Wish",content['Wish'])
        classmate.set("Phone",content['Phone'])
        try:
            f = request.files['Photo']
            cloudfile=leancloud.File(secure_filename(f.filename),f.read())
            cloudfile.save()
            classmate.set('Photo',cloudfile)
        except:
            pass
        classmate.save()
    else:
        success=False
    return render_template('index.html',beian=beian,title=title,count=str(number),success=success)
# 后台管理部分
@app.route('/admin')
def admin():
    global Classmate
    global beian
    global title
    global limit
    query=Classmate.query
    query.exists('Name')
    query.ascending('createdAt')
    count=int(query.count())
    Pages=request.args.get('Pages')
    if Pages==None:
        Pages=1
    else:
        Pages=int(Pages)
    query.skip(limit*(int(Pages)-1))
    query.limit(limit)
    data_list=query.find()
    list_page=math.ceil(count/limit)
    show_data=[]
    for data in data_list:
        temp_data={}
        temp_data['ID']=data.id
        temp_data['createdAt']=str(data.created_at)[:-13]
        temp_data['Name']=data.get('Name')
        temp_data['Birthday']=data.get('Birthday')
        temp_data['Address']=data.get('Address')
        temp_data['Sex']=data.get('Sex')
        temp_data['Wechat']=data.get('Wechat')
        temp_data['QQ']=data.get('QQ')
        temp_data['Wish']=data.get('Wish')
        temp_data['Phone']=data.get('Phone')
        if data.get('Photo') is not None:
            photo=leancloud.File.create_without_data(data.get('Photo').id)
            photo.fetch()
            temp_data['Photo']=data.get('Photo').url
            temp_data['Small_photo']=photo.get_thumbnail_url(300,400)
        show_data.append(temp_data)
    return render_template('admin.html',beian=beian,title=title+"管理页面",data=show_data,count=int(count),Pages=Pages,list_page=list_page)
# 导出Excel部分
@app.route('/export')
def export():
    global Classmate
    width_list=[]
    query=Classmate.query
    query.exists('Name')
    query.ascending('createdAt')
    data_list=query.find()
    output = BytesIO()
    filename=str(uuid.uuid1())+".xlsx"
    excel=xlsxwriter.Workbook(output)
    worksheet = excel.add_worksheet("数据结果")
    worksheet.write(0,0,"姓名")
    worksheet.write(0,1,"生日")
    worksheet.write(0,2,"地址")
    worksheet.write(0,3,"性别")
    worksheet.write(0,4,"手机")
    worksheet.write(0,5,'微信')
    worksheet.write(0,6,"QQ")
    worksheet.write(0,7,"祝福语")
    worksheet.write(0,8,"照片")
    row=1
    for data in data_list:
        worksheet.write(row,0,data.get('Name'))
        worksheet.write(row,1,data.get('Birthday'))
        worksheet.write(row,2,data.get('Address'))
        worksheet.write(row,3,data.get('Sex'))
        worksheet.write(row,4,data.get('Phone'))
        worksheet.write(row,5,data.get('Wechat'))
        worksheet.write(row,6,data.get('QQ'))
        worksheet.write(row,7,data.get('Wish'))
        if not data.get('Photo'):
            pass
        else:
            photo=data.get('Photo')
            photo_content=BytesIO(requests.get(photo.url).content)
            im=Image.open(photo_content)
            width,high=im.size
            width=int(width)
            high=int(high)
            worksheet.insert_image("I"+str(row+1),photo.name,{'image_data': photo_content})
            worksheet.set_row(row,high)
            width_list.append(width)
        row=row+1
    worksheet.set_column(8,9,max(width_list))
    excel.close()
    response = Response(output.getvalue())
    response.headers['Content-Type']="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    response.headers['Content-Disposition'] = 'attachment; filename={}'.format(filename.encode().decode('latin-1'))
    return response
# 图表显示部分
@app.route('/charts')
def charts():
    global Classmate
    if request.args.get('Type')=="Sex":
        boy=int(Classmate.query.equal_to('Sex','男').count())
        girl=int(Classmate.query.equal_to('Sex','女').count())
        secret=int(Classmate.query.equal_to('Sex','保密').count())
        charts=(
            Pie(init_opts=opts.InitOpts(page_title="男女性别比例",js_host="https://cdn.staticfile.org/echarts/4.8.0/",width="600px",height="300px"))
            .set_global_opts(title_opts=opts.TitleOpts(title='男女性别比例'))
            .add("",[['男',boy],['女',girl],['保密',secret]],label_opts=opts.LabelOpts(is_show=True))
        )
        return Markup(charts.render_embed())
    elif request.args.get('Type')=="Birth_year":
        query=Classmate.query
        query.exists('Birthday')
        query.select('Birthday')
        data_list=query.find()
        year_list=[]
        for temp_data in data_list:
            year_list.append(int(temp_data.get('Birthday')[:4]))
        Counter=collections.Counter(year_list)
        show_data=[]
        for key in Counter:
            temp_data=[]
            temp_data.append(key)
            temp_data.append(Counter[key])
            show_data.append(temp_data)
        charts=(
            Pie(init_opts=opts.InitOpts(page_title="出生年份比例",js_host="https://cdn.staticfile.org/echarts/4.8.0/",width="600px",height="300px"))
            .set_global_opts(title_opts=opts.TitleOpts(title='出生年份比例'))
            .add("",show_data,label_opts=opts.LabelOpts(is_show=True))
        )
        return Markup(charts.render_embed())
    else:
        abort(404)
# 错误处理部分
@app.errorhandler(404)
def error(error):
    return render_template('error.html'),404
if __name__ == '__main__':
    app.run()